package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理与指定客户端的HTTP交互
 * HTTP交互采取一问一答,因此这里分为三步完成一次交互过程:
 * 1:解析请求
 * 2:处理请求
 * 3:响应客户端
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);


            //2处理请求
            //通过请求对象获取浏览器URL中的抽象路径部分
            /*
                http://localhost:8088/myweb/index.html
                http://localhost:8088/myweb/classTable.html

                以下两种就是404情况
                http://localhost:8088/myweb/123.html 不存在的资源
                http://localhost:8088  定位的是一个目录
             */
            String path  = request.getUri();
            File file = new File("./webapps"+path);
            if(file.exists()&&file.isFile()){
                //资源存在
                response.setEntity(file);
            }else{
                //资源不存在
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntity(file);
            }

            //3发送响应
            response.flush();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互完毕后与客户端断开链接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}






